<template>
  <doc-alert title="【交易】门店佣金提现" url="https://doc.iocoder.cn/mall/trade-brokerage/" />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="服务商名称" prop="partnerName">
        <el-input
          v-model="queryParams.partnerName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item label="提现类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择提现类型"
          clearable
          class="!w-240px"
        >
          <el-option label="代理商提现" :value="1" />
          <el-option label="门店提现" :value="2" />
          <el-option label="服务商提现" :value="3" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BROKERAGE_WITHDRAW_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="left" prop="id" min-width="60px" />
      <el-table-column label="服务商信息" align="left" min-width="120px">
        <template #default="scope">
          <div>编号：{{ scope.row.servicePartnerId }}</div>
          <div>名称：{{ scope.row.servicePartnerName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="提现金额" align="left" prop="price" min-width="100px">
        <template #default="scope">
          <div>金　额：￥{{ fenToYuan(scope.row.price) }}</div>
          <div v-if="scope.row.feePrice > 0">手续费：￥{{ fenToYuan(scope.row.feePrice) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="提现方式" align="left" prop="type" min-width="120px">
        <template #default="scope">
          <div v-if="scope.row.type === 1">
            <div>钱包</div>
          </div>
          <div v-else-if="scope.row.type === 2">
            <div>银行卡</div>
            <div v-if="scope.row.bankName">银行：{{ scope.row.bankName }}</div>
            <div v-if="scope.row.bankAddress">地址：{{ scope.row.bankAddress }}</div>
          </div>
          <div v-else-if="scope.row.type === 3">
            <div>收款码</div>
            <div v-if="scope.row.bankName">名称：{{ scope.row.bankName }}</div>
            <div v-if="scope.row.accountQrCodeUrl">
              <el-image
                :src="scope.row.accountQrCodeUrl"
                style="width: 50px; height: 50px"
                :preview-src-list="[scope.row.accountQrCodeUrl]"
                preview-teleported
                fit="cover"
              />
            </div>
          </div>
          <div v-else> 未知类型 </div>
        </template>
      </el-table-column>
      <el-table-column
        label="申请时间"
        align="left"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="备注" align="left" prop="remark" />
      <el-table-column label="状态" align="left" prop="status" min-width="120px">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
          <div v-if="scope.row.auditTime" class="text-xs mt-1">
            时间：{{ formatDate(scope.row.auditTime) }}
          </div>
          <div v-if="scope.row.auditReason" class="text-xs">
            原因：{{ scope.row.auditReason }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="150px" fixed="right">
        <template #default="scope">
          <template v-if="scope.row.status === BrokerageWithdrawStatusEnum.AUDITING.status">
            <el-button link type="primary" @click="handleApprove(scope.row.id)"> 通过 </el-button>
            <el-button link type="danger" @click="openForm(scope.row.id)"> 驳回 </el-button>
          </template>
          <template v-else-if="scope.row.status === 10 && scope.row.type !== 1">
            <el-button link type="success" @click="openTransferVoucherForm(scope.row)">
              上传转账凭证
            </el-button>
          </template>
          <template v-else-if="scope.row.status === 11">
            <el-button
              link
              type="primary"
              :disabled="scope.row.type === 1"
              @click="openViewForm(scope.row)"
            >
              查看
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ServiceCommissionWithdrawRejectForm ref="formRef" @success="getList" />

  <!-- 上传转账凭证弹窗 -->
  <ServiceTransferVoucherForm ref="transferVoucherFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getDictLabel, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import * as AgentCommissionWithdrawApi from '@/api/mall/agent'
import ServiceApi from '@/api/application/service'
import ServiceCommissionWithdrawRejectForm from './serviceCommissionWithdrawRejectForm.vue'
import ServiceTransferVoucherForm from './serviceTransferVoucherForm.vue'
import { BrokerageWithdrawStatusEnum, BrokerageWithdrawTypeEnum } from '@/utils/constants'
import { fenToYuan } from '@/utils'

defineOptions({ name: 'StoreCommissionWithdraw' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  partnerName: null as any,
  // type: null as any,
  status: null as any,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ServiceApi.getServiceWithdrawPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (id: number) => {
  formRef.value.open(id)
}

/** 上传转账凭证操作 */
const transferVoucherFormRef = ref()
const openTransferVoucherForm = (row: any) => {
  transferVoucherFormRef.value.open(row)
}

/** 查看转账凭证操作 */
const openViewForm = (row: any) => {
  transferVoucherFormRef.value.open(row, true) // 第二个参数为true表示只读模式
}

/** 获取状态文本 */
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '审核中'
    case 10:
      return '审核通过'
    case 11:
      return '提现成功'
    case 20:
      return '审核不通过'
    case 21:
      return '提现失败'
    default:
      return '未知状态'
  }
}

/** 获取状态标签类型 */
const getStatusTagType = (status: number) => {
  switch (status) {
    case 0:
      return 'warning' // 审核中 - 橙色
    case 10:
      return 'primary' // 审核通过 - 蓝色
    case 11:
      return 'success' // 提现成功 - 绿色
    case 20:
      return 'danger' // 审核不通过 - 红色
    case 21:
      return 'danger' // 提现失败 - 红色
    default:
      return 'info' // 未知状态 - 灰色
  }
}

/** 审核通过 */
const handleApprove = async (id: number) => {
  try {
    // 先弹出确认对话框，用户确认后再显示loading
    await message.confirm('确定要审核通过吗？')
    loading.value = true
    await ServiceApi.approveServiceWithdraw(id)
    await message.success(t('common.success'))
    await getList()
  } catch (error) {
    // 如果用户取消确认，不需要处理
  } finally {
    loading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
